package com.airspyar;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import android.util.Log;

public class SynchronizedClock {
	private SynchronizedClock(){}
	private static SynchronizedClock instance=null;
	private long offset=0;
	private static boolean initialized=false;
	
	public static void initialize(){
		if(initialized)
			return;
		
		instance=new SynchronizedClock();
		
		try{
			URL url=new URL("http://www.flightradar24.com/js/_js.php");
			BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));
			String line, exp="var timeServer = ";
			while((line=br.readLine())!=null){
				int index=line.indexOf(exp);
				if(index!=-1){
					String substr=line.substring(index+exp.length(), line.indexOf(";", index));
					long time=Long.parseLong(substr);
					instance.setCurrentTime(time);
					initialized=true;
					return;
				}
			}
		}catch(Exception e){
			if(AirSpyActivity.LOG_ERROR)
				Log.e("SynchronizedClock exception", e.getMessage());
		}
	}
	
	public static long currentTimeMillis(){
		return System.currentTimeMillis()+instance.offset;
	}
	
	private void setCurrentTime(long millis){
		offset=millis-System.currentTimeMillis();
	}
	
	public static boolean isInitialized(){
		return initialized;
	}
}
